<template>
    <div class="m">
        <h3> AI审计配置 AI Audit Config </h3>
        <div class="part">
                <h4> 整合,审计 Compile,Audit </h4>

                <div>
                    <div style="margin-bottom: 1em;">
                        <el-text >
                            启动AI审计请执行以下步骤：
                            1. 停止操作记录监控
                            2. 整合操作记录 （这会针对存储空间对操作记录进行一些优化）
                            3. 开启AI操作记录审计 （该操作将会对每一条行为记录进行评估）
                            4. (可选) 重新启动操作记录监控
                        </el-text>
                    </div>
                    <div style="margin-bottom: 8px;">

                        <el-row>
                            <el-col :span="8">
                                <el-select v-model="aParams.type" placeholder="选择审计模型 Select" style="width: 240px; margin-right: 10px;">
                                    <el-option
                                        v-for="item in auditTypes"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                </el-select>
                                <Transition>
                                    <div> <el-input v-if="aParams.type === 'ollama'" v-model="aParams.url" style="width: 240px" placeholder="localhost:11434" /> </div>
                                </Transition>

                                <el-input
                                    v-if="aParams.type === 'gemini'"
                                    v-model="aParams.gk" style="width: 240px" placeholder="aParams.gk" />
                            </el-col>

                            <el-col :span="3" style="margin-left: 5px;display: flex; align-items: center;"
                            > <div >
                                    <el-text > 批处理数 N Batch </el-text>
                                </div>
                            </el-col>
                            <el-col :span="8" style="margin-bottom: 3px;">
                                <el-slider v-model="aParams.Nb" show-input />
                            </el-col>
                        </el-row>

                    </div>


                    <el-steps style="max-width: 600px; margin-bottom: 5px;" :active="auditStep" finish-status="success">
                        <el-step title="Step 1" description="暂停监控" />
                        <el-step title="Step 2" description="整合记录" />
                        <el-step title="Step 3" description="AI审计记录" />
                    </el-steps>

                    <el-row :gutter="20">
                        <el-col :span="7">
                            <el-switch
                                v-model="streaming"
                                active-text="操作监控开启 Streaming On"
                                inactive-text="操作监控关闭 Streaming Off"
                            />
                        </el-col>

                        <el-col :span="9">
                            <el-button type="warning" @click="clickCompile" :disabled="auditStep !== 1">
                                <span class="text" v-waves style="margin-right: 1em;">
                                    整合 compile</span>
                                <el-icon><DArrowRight /></el-icon>
                            </el-button>

                            <el-button type="success" @click="clickAudit" :disabled="auditStep !== 2">
                                <span class="text" v-waves style="margin-right: 1em;">
                                    开始审计 audit</span>
                                <el-icon><DArrowRight /></el-icon>
                            </el-button>

                            <el-button type="" @click="clickAuditAbort" v-if="registering">
                                <span class="text" v-waves style="margin-right: 1em;">
                                    停止审计 abort audition</span>
                                <el-icon><DArrowRight /></el-icon>
                            </el-button>
                        </el-col>

                        <el-col :span="5">
                        </el-col>
                    </el-row>
                </div>

                <el-row :gutter="20" style="margin: 1em;">
                    <el-col :span="9">
                        <el-progress
                            v-if="streaming"
                            :percentage="20"
                            status="info"
                            :indeterminate="true"
                            :duration="2" />
                        <el-progress
                            v-if="compiling"
                            :percentage="100"
                            status="warning"
                            :indeterminate="true"
                            :duration="2" />
                        <el-progress
                            v-if="registering"
                            :percentage="100"
                            status="success"
                            :indeterminate="true"
                            :duration="2" />
                    </el-col>
                    <el-col :span="4">
                        <el-text class="shining-status"> {{loadingText}} </el-text>
                    </el-col>
                </el-row>

                <div style="width: 50%; margin: 1em">
                </div>
            </div>

        <h3> 区块链配置 Chain Config </h3>
        <div class="part">
            <el-switch
                v-model="enabled"
                active-text="启用链存证 Enable"
                inactive-text="停用链存证 Disable"
            />
        </div>

        <Transition name="slide-fade">
            <div class="part" v-if="enabled">
                <h4> 节点连接 Node Connection </h4>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-input
                            v-model="endpoint_url"
                            style="max-width: 400px"
                            placeholder="localhost:7777"
                        >
                            <template #prepend>http://</template>
                        </el-input>
                    </el-col>
                    <el-col :span="3">
                        <el-button type="primary" @click="clickConnect">
                            <span class="text" v-waves style="margin-right: 1em;">
                                连接 connect</span>
                            <el-icon><DArrowRight /></el-icon>
                        </el-button>
                    </el-col>
                    <Transition>
                        <div>
                            <el-col :span="5" v-if="connecting" >
                                <el-progress
                                    :percentage="100"
                                    status="success"
                                    :indeterminate="true"
                                    :duration="1"
                                />
                                <!-- <LottieAnimation
                                     :animation-data="LoadingJSON"
                                     class="a-loading"
                                     :auto-play="true"
                                     :loop="true" :speed="1"
                                     ref="anim" /> -->
                            </el-col>
                        </div>
                    </Transition>
                </el-row>
            </div>
        </Transition>

        <Transition name="slide-fade">
            <div class="part" v-if="enabled">
                <h4> 整合,存证 Compile,Register </h4>

                <el-select
                    style="width: 30%; margin-bottom: 1em;"
                    v-model="rs.selectedMethod" placeholder="please select your zone">
                    <span v-for="item in rs.methodList" :key="item.value">
                        <el-option :label="item.label" :value="item.value" />
                    </span>
                        <!-- <el-option label="Zone one" value="shanghai" /> -->
                        <!-- <el-option label="Zone two" value="beijing" /> -->
                </el-select>

                <div v-if="rs.selectedMethod === 'manual'">
                <div style="margin-bottom: 1em;">
                    <el-text >
                        手动存证请执行以下步骤：
                        1. 停止操作记录监控
                        2. 整合操作记录 （这会针对存储空间对操作记录进行一些优化）
                        3. 存证操作记录 （这会将操作记录存证到区块链）
                        4. (可选) 重新启动操作记录监控
                    </el-text>
                </div>

                <el-steps style="max-width: 600px; margin-bottom: 5px;" :active="registerStep" finish-status="success">
                    <el-step title="Step 1" description="暂停监控" />
                    <el-step title="Step 2" description="整合记录" />
                    <el-step title="Step 3" description="存证已整合记录" />
                </el-steps>

                <el-row :gutter="20">
                    <el-col :span="7">
                        <el-switch
                v-model="streaming"
                active-text="操作监控开启 Streaming On"
                inactive-text="操作监控关闭 Streaming Off"
                />
                    </el-col>

                    <el-col :span="6">
                        <el-button type="warning" @click="clickCompile" :disabled="registerStep !== 1">
                            <span class="text" v-waves style="margin-right: 1em;">
                                整合 compile</span>
                            <el-icon><DArrowRight /></el-icon>
                        </el-button>

                        <el-button type="success" @click="clickRegister" :disabled="registerStep !== 2">
                            <span class="text" v-waves style="margin-right: 1em;">
                                存证 register</span>
                            <el-icon><DArrowRight /></el-icon>
                        </el-button>
                    </el-col>

                    <el-col :span="5">
                    </el-col>
                </el-row>
                </div>

                <el-row :gutter="20" style="margin: 1em;">
                    <el-col :span="9">
                        <el-progress
                            v-if="streaming"
                            :percentage="20"
                            status="info"
                            :indeterminate="true"
                            :duration="2" />
                        <el-progress
                            v-if="compiling"
                            :percentage="100"
                            status="warning"
                            :indeterminate="true"
                            :duration="2" />
                        <el-progress
                            v-if="registering"
                            :percentage="100"
                            status="success"
                            :indeterminate="true"
                            :duration="2" />
                    </el-col>
                    <el-col :span="4">
                        <el-text class="shining-status"> {{loadingText}} </el-text>
                    </el-col>
                </el-row>

                <div style="width: 50%; margin: 1em">
                </div>
                <div style="margin-left: 1em">
                    <h5> 系统公钥 System Public Key (Ed25519) </h5>
                    <el-text style="margin-left: 1em">
                    <TT>
                        -----BEGIN PUBLIC KEY-----
                        MCowBQYDK2VwAyEAeCAO49pN75vhyp3MjpY+sDNrVog0ViKJkTYaKw/z+rc=
                        -----END PUBLIC KEY-----
                    </TT>
                    </el-text>
                </div>
            </div>
        </Transition>

<Transition name="slide-fade">
            <div class="part" v-if="enabled && ni">
                <h4> 节点信息 Node Info </h4>

                <el-row :gutter="20" class="d1" style="margin-left: 2em;">
                    <el-col :span="5"><TT> 共识算法 Consensus : </TT> </el-col>
                    <el-col :span="4"> <TT> {{ni?.cnsss}} </TT> </el-col>
                    <el-col :span="4"> <TT> Primary节点: </TT> </el-col>
                    <el-col :span="2"> <TT>  {{ni?.is_primary}} </TT> </el-col>
                </el-row>

                <el-row :gutter="20" class="d1" style="margin-left: 2em;">
                    <el-col :span="5"> <TT> 总交易数 txCount: </TT> </el-col>
                    <el-col :span="4"> <TT> {{ni?.txs_count}} </TT> </el-col>
                    <el-col :span="4"> <TT> 区块高度 blockCount : </TT> </el-col>
                    <el-col :span="2"> <TT> {{ni?.latest_blk.number + 1}} </TT> </el-col>
                </el-row>

                <el-row :gutter="20" class="d1" style="margin-left: 2em;">
                    <el-col :span="5"> <TT> 节点公钥 publicKey: </TT> </el-col>
                    <el-col :span="4"> <TT> {{ni?.listened_endpoint.pk}}</TT> </el-col>
                    <el-col :span="4"> <TT> 节点 endpoint: </TT> </el-col>
                    <el-col :span="2"> <TT> {{ni?.listened_endpoint.addr_port}}</TT> </el-col>
                </el-row>

                <el-row :gutter="20" class="" style="margin-left: 2em;margin-bottom: 1em;">
                    <el-col :span="4"> <TT> 节点证书: </TT> </el-col>
                    <el-col :span="2"> <TT> {{ni?.cert}} </TT> </el-col>
                </el-row>

            </div>
        </Transition>

<Transition name="slide-fade">
    <div class="part" v-if="enabled && ni">
                <h4> 最新区块： Latest Block</h4>

                <el-row :gutter="20" class="d1" style="margin-left: 2em;">
                    <el-col :span="5"><TT> 区块号 number: </TT> </el-col>
                    <el-col :span="4"> <TT>  {{ni.latest_blk.number}} </TT> </el-col>
                    <el-col :span="4"> <TT> 交易数 txCount: </TT> </el-col>
                    <el-col :span="2"> <TT> {{ni.latest_blk.txs.length}}</TT> </el-col>
                </el-row>

                <el-row :gutter="20" class="d1" style="margin-left: 2em;">
                    <el-col :span="5"><TT> 上级哈希 parentHash: </TT> </el-col>
                    <el-col :span="4"> <TT>  {{ni.latest_blk.parentHash}} </TT> </el-col>
                </el-row>

                <el-row :gutter="20" class="d1" style="margin-left: 2em;">
                    <el-col :span="5"> <TT> 哈希 hash: </TT> </el-col>
                    <el-col :span="4"> <TT> {{ni.latest_blk.hash}} </TT> </el-col>
                </el-row>

                <div style="margin-left:2em;">
                <h5>包含交易 Txs:</h5>
                <vue-json-pretty :data="ni.latest_blk.txs" />
                <h5>交易回执 TxReceipts:</h5>
                <vue-json-pretty :data="ni.latest_blk.txReceipts" />
                </div>

            </div>
        </Transition>

        <LottieAnimation :animation-data="FarmerJSON"
class="anim" :auto-play="true" :loop="true" :speed="1" ref="anim" />

        <LottieAnimation :animation-data="R1JSON"
class="anim r1" :auto-play="true" :loop="true" :speed="0.05" ref="anim" />

        <LottieAnimation :animation-data="R2JSON" class="anim r2" :auto-play="true" :loop="true" :speed="0.02" ref="anim" />

        <LottieAnimation :animation-data="R3JSON" class="anim r3" :auto-play="true" :loop="true" :speed="0.05" ref="anim" />

        <!-- <LottieAnimation :animation-data="R4JSON" class="anim r4" :auto-play="true" :loop="true" :speed="0.05" ref="anim" /> -->
    </div>


</template>

<script setup lang="ts">
 import { LottieAnimation } from "lottie-web-vue";
 import FarmerJSON from "@/assets/farmer.json";
 import R1JSON from "@/assets/ShapesLoader.json";
 import R2JSON from "@/assets/ShapesLoader1.json";
 import R3JSON from "@/assets/CircularLoader.json";
 import R4JSON from "@/assets/CircularLoader1.json";

 // import LoadingJSON from "@/assets/loading1.json";
 import LoadingJSON from "@/assets/loading2.json";
 import { fetchNodeInfo, rIsStreaming, rToggle, rFold, rRegister, rStartAudit,
          rAuditPerc, rAuditAbort} from '@/api/hi_api';
 import VueJsonPretty from 'vue-json-pretty';
 import 'vue-json-pretty/lib/styles.css';

 import { reactive, ref, onMounted,watch, computed} from 'vue';
 import { DArrowRight } from '@element-plus/icons-vue';
 import vWaves from '@/directive/waves'; // 水波纹指令
 import {Tween, Easing} from '@tweenjs/tween.js';
 import { useHiStore } from '@/store/hi-store'

 const aParams = reactive({
     type : '', url: '', gk: 'AIzaSyCC3yPVcvZMbiF7IBCxKU-psxW2ESsmrVA', Nb: 5
     })
 const auditTypes = [
     {label: '测试 Mock', value: 'mock'},
     {label: 'ollama 3.2', value: 'ollama'},
     {label: 'deepseek r1 (中文）', value: 'qwen25'},
     {label: 'gemini 1.5', value: 'gemini'}
 ]

 class RegisterStrategy {
     selectedMethod: string;
     methodList: string[];
     // '每小时 Every Hour',
     // '每6小时 Every 6 Hours',
     // '每天凌晨 Every Day 00:00',
     // '每周一凌晨 Every Monday 00:00',
     // '每月一号凌晨 Every 1st Day 00:00'
     constructor(){
         this.methodList = [
             {label: '手动 Manual', value: 'manual'},
             {label: '每小时 Every Hour', value: 'everyHour'},
             {label: '每6小时 Every 6 Hours', value: 'every6Hours'},
             {label: '每天凌晨 Every Day 00:00', value: 'everyDay'},
             {label: '每周一凌晨 Every Monday 00:00', value: 'everyMonday'},
             {label: '每月一号凌晨 Every 1st Day 00:00', value: 'every1stDay'}
         ]
         this.selectedMethod = this.methodList[0].value;
      }
 };

 let rs = reactive(new RegisterStrategy());
 watch(rs, (x) => {
     console.log('🦜: selected method: ', x.selectedMethod);
     if (x.selectedMethod == 'manual'){
         loadingText.value = 'Streaming On';
     }else{
         loadingText.value = 'Streaming On with Auto Registeration';
     }
 });



 let anim = ref();

 let enabled = ref(true);
 watch(enabled, async (x) => {
     console.log('🦜: enabled', x);
     if (!x){
         ni.value = null;
         // store.$patch({nodeInfo: null})
     }
 });

 let streaming = ref(true);
 let compiling = ref(false);
 let registering = ref(false);

 let loadingText = ref('Streaming On');


 const registerStep = ref(0);
 const auditStep = ref(0);

 function setBothStep(x){
     registerStep.value = x;
     auditStep.value = x;
 }

 // 0: streaming, 1. stopped, 2, compiled, 3, registered
 watch(streaming, async (x) => {
     // console.log('🦜: streaming', x);
     let r = await rIsStreaming();
     if (r.data === x){
         ElMessage({
             message: '操作监控状态不一致,但已自动修复 Streaming status inconsistent, but auto-fixed',
             type: 'warning',
             duration: 5000
         })
     }else{
         await rToggle(x);
         ElMessage({
             message: `操作监控已${x ? '开启' : '关闭'} Streaming ${x ? 'On' : 'Off'}`,
             type: 'success',
             duration: 5000
         })
     }

     if (x){
         // registerStep.value = 0; auditStep.value = 0;
         setBothStep(0);
         loadingText.value = 'Streaming On';
         // compiled.value = false;
         // registered.value = false;
     }else{
         loadingText.value = 'Streaming Off';
         // registerStep.value = 1;
         setBothStep(1);
     }
 });

 let endpoint_url = ref('');
 let connecting = ref(false);


 const store = useHiStore()
 const ni = ref(store.nodeInfo);
 // 🦜: case matter

 function sleep(sec){
     return new Promise((resolve, reject) => {
         setTimeout(() => {
             resolve();
         }, sec * 1000);
     });
 }

 const clickAudit = async () => {
     console.log('🦜: auditing')
     registering.value = true;
     loadingText.value = 'Auditing';

     /* 🦜: Here's the logic, we issue an rStartAudit(), and then for each
        second, we issue an rAuditPerc which returns a percentage, when that's
        100, we stop. */
     const m = await rStartAudit(aParams)
     ElMessage({
         message: `${m.data} %`,
         type: 'success',
         duration: 1000
     })
     let r = 0;
     do {
         await sleep(1);
         const o = await rAuditPerc();
         r = o.data;// <- 🐢 a number showing the percentage...if it's -1, we stop
         if (r < 0){
             ElMessage({
                 message: `Audit aborted with: ${r} %`,
                 type: 'success',
                 duration: 1000
             })
             break;
         }else{
             ElMessage({
                 message: `Now audit: ${r} %`,
                 type: 'success',
                 duration: 1000
             })
         }
     }while(r < 100);

     registering.value = false;
     loadingText.value = 'Audited';
     auditStep.value = 3;
     console.log('🦜: audited')
 }

 const clickAuditAbort = async () => {
     await rAuditAbort();
 }

 const clickCompile = async () => {
     console.log('🦜: compiling')
     compiling.value = true;
     loadingText.value = 'Compiling';
     await sleep(3)
     const r = await rFold()// {data: number}
     // registerStep.value = 2;
     setBothStep(2);
     compiling.value = false;
     loadingText.value = 'Compiled';
     console.log('🦜: compiled')

     let msg = `整合成功 Compiled successfully: ${r.data} record(s) folded`
     ElMessage({
         message: msg,
         type: 'success',
         duration: 5000
     })
 };

 const clickRegister = async () => {
     console.log('🦜: registering')
     registering.value = true;
     loadingText.value = 'Registering';
     await sleep(3)// 🦜 : tbh registering is faster than I imaging...
     const r = await rRegister()// {data: number}
     registering.value = false;
     loadingText.value = 'Registered';
     registerStep.value = 3;
     console.log('🦜: registered')

     let msg = `存证成功 Registered successfully: ${r.data} registered`
     ElMessage({
         message: msg,
         type: 'success',
          duration: 5000
     })
 };

 const clickConnect = async () => {
     console.log('🦜: connecting')
     connecting.value = true;
     const r = await fetchNodeInfo('');
     await sleep(3)
     if (r.code !== 0){
          connecting.value = false;
          ElMessage({
              message: '连接失败 Connection failed',
              type: 'error',
              duration: 5000
          })
          return;
     }

     ni.value = r.data;
     // store.$patch({nodeInfo: ni})

     connecting.value = false;
     console.log('🦜: connected node: ', ni)

     // setTimeout(() => {
     //     connecting.value = false;
     // }, 5000);
 };

 onMounted(async () => {
     // console.log(`🦜 : mounted with store`, store.nodeInfo)

     // ni.value = null;
     setTimeout(() => {
         console.log(anim.value.goToAndPlay(150, true));
         anim.value;
     }, 500);

     // r1's rotation
     // --------------------------------------------------
     const ar1 = document.querySelector('.anim.r1');
     const ar2 = document.querySelector('.anim.r2');
     const ar3 = document.querySelector('.anim.r3');
     // const ar4 = document.querySelector('.anim.r4');
     // console.log('🦜: ar1', ar1);
     // rotate the .anim.r1's rotation
     const tween = new Tween({rotation: 0})
         .to({rotation: 360}, 200000)
         .onUpdate((obj) => {
             let r = obj.rotation;
             ar1.style.transform = `rotate(${r}deg)`;
             ar2.style.transform = `rotate(${r}deg)`;
             ar3.style.transform = `rotate(${r}deg)`;
             // ar4.style.transform = `rotate(${r}deg)`;
         })
         .repeat(Infinity)
         .start();


     function update(time) {
         requestAnimationFrame(update);
         tween.update(time);
     }
     requestAnimationFrame(update);
 });


</script>

<style lang="sass" scoped>
 .m
     padding-left: 10px
 .part
     padding: 10px
     border-bottom: 1px solid #ccc

 /* transition: property name | duration | easing function | delay */
 .slide-fade-enter-active
     transition: all 0.4s ease-out
 .slide-fade-leave-active
     transition: all 0.7s cubic-bezier(1, 0.5, 0.8, 1)
 .slide-fade-enter-from,
 .slide-fade-leave-to
     transform: translateX(20px)
     opacity: 0

 .slide-fade-leave-active:nth-of-type(2)
     transition-delay: 0.5s!important
 .slide-fade-leave-active:nth-of-type(3)
     transition-delay: 0.2s!important

 /* .slide-fade-enter-active:nth-of-type(2)
    transition-delay: 0.2s!important
    .slide-fade-enter-active:nth-of-type(3)
    transition-delay: 0.5s!important */

 /* we will explain what these classes do next! */
 .v-enter-active,
 .v-leave-active
     transition: opacity 0.5s ease

 .v-enter-from,
 .v-leave-to
     opacity: 0



 /* .p2-flex
    display: flex
    align-items: center
    justify-content: space-around
    width: 50% */

 .a-loading
     width: 80px
     height: 80px
     position: absolute
     bottom: 30%
     left: 37%
     opacity: inherit!important

 .d1
     border-bottom: 1px solid var(--el-color-primary-light-9)
     margin-bottom: 10px
     padding-right: 0%
     width: 90%
     padding-bottom: 5px
     opacity: 100%


 .anim
     position: fixed
     width: 500px
     height: 500px
     bottom: 0vh
     left: 70vw
     opacity: 0%
     z-index: -1

 .anim.r1
     width: 1300px
     height: 1300px
     top: -70vh
     left: 50vw
     rotate: 90deg
     opacity: 0%

 .anim.r2
     width: 700px
     height: 700px
     top: 0vh
     left: 0vw
     opacity: 0%

 .anim.r3
     top: -10vh
     left: 20vw
     opacity: 0%

 .anim.r4
     top: -10vh
     left: 50vw
     opacity: 0%

 @keyframes blink 
     0%
         opacity: 1
     50% 
         opacity: 0
     100% 
         opacity: 1

 .shining-status
     animation: blink 2s infinite
     position: relative
     bottom: 3px

</style>
